package com.buba.controller;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class MyController {

    /**
     * 默认首页面
     * @param model
     * @return
     */
    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,shiro!");
        return "index";

    }

    /**
     * 添加页面
     * @return
     */
    @RequestMapping({"/user/add"})
    public String add(){
        return "user/add";
    }


    /**
     * 修改页面
     * @return
     */
    @RequestMapping({"/user/upd"})
    public String upd(){
        return "user/upd";
    }

    /**
     * 跳转登录页面
     * @return
     */
    @RequestMapping({"/toLogin"})
    public String toLogin(){
        return "login";
    }

    /**
     * 登录方法
     * @param userName
     * @param password
     * @param model
     * @return
     */
    @RequestMapping({"/login"})
    public String login(String userName,String password,Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        //执行登录的方法，如果没有异常表示ok
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException uae) {//用户名错误
            model.addAttribute("msg","用户名错误");
            return "login";
        } catch (IncorrectCredentialsException ice) {//密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        } catch (LockedAccountException lae) {//用户被锁定
            model.addAttribute("msg","用户被锁定");
            return "login";
        }
    }

    /**
     * 未授权方法
     * @return
     */
    @RequestMapping({"/unAuthorized"})
    @ResponseBody
    public String unAuthorized(){
        return "未经授权无法访问此页面！！！";
    }

    /**
     * 登出  这个方法没用到,用的是shiro默认的logout
     * @param model
     * @return
     */
    @RequestMapping("/logout")
    public String logout(Model model) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        model.addAttribute("msg","安全退出！");
        return "login";
    }

}
